<?php

namespace App\Model;

use Database\Model;
use Exception;
use Kiri;
use Kiri\Redis\Redis;
use Kiri\Router\Base\AuthorizationInterface;

/**
 * Class User
 * @package Inter\mysql
 *
 * @property $id
 * @property $nickname
 * @property $email
 * @property $password
 * @property $avatar
 * @property $createTime
 * @property $modifyTime
 * @sql
 */
class User extends Model implements AuthorizationInterface
{

    use FakerData;


    public string $primary = 'id';


    protected string $table = 'user';


    protected string $connection = 'db';


    /**
     * @return array
     */
    public function rules(): array
    {
        return [
            [['nickname', 'email', 'password', 'avatar'], 'string'],
            ['nickname', 'maxLength' => 100],
            ['password', 'maxLength' => 96],
            ['avatar', 'maxLength' => 255],
            [['createTime', 'modifyTime'], 'maxLength' => 10],
            [['createTime', 'modifyTime'], 'int'],
        ];
    }


    /**
     * @return static
     */
    public function getIdentity(): static
    {
        return $this;
    }


    /**
     * @return string|int
     */
    public function getUniqueId(): string|int
    {
        return $this->id;
    }


    /**
     * @param string $key
     * @param int $timeout
     * @return bool
     * @throws Exception
     */
    public function lock(string $key, int $timeout): bool
    {
        $redis = Kiri::getDi()->get(Redis::class);
        $name  = 'user:lock:' . $this->id . (empty($key ? '' : ':' . $key));
        return $redis->lock($name, $timeout);
    }

    /**
     * @param null|string $key
     * @return bool
     * @throws Exception
     */
    public function unlock(string $key = null): bool
    {
        $redis = Kiri::getDi()->get(Redis::class);
        $name  = 'user:lock:' . $this->id . (empty($key ? '' : ':' . $key));
        return $redis->del($name);
    }

}
